package com.spsoft.core.utils;

import com.alibaba.fastjson.JSONArray;
import com.spsoft.core.enums.ResponseEnum;
import com.spsoft.core.exception.LoginException;
import com.spsoft.core.model.bo.TokenUser;

public class SecurityUtils {

    /**
     * 获取系统用户名字
     *
     */
    public static String getUsername()
    {
       return getTokenUser().getUserName();
    }

    /**
     * 获取系统用户账号
     *
     */
    public static String getUserCode()
    {
        return getTokenUser().getUserCode();
    }

    /**
     * 当前机构编码
     *
     */
    public static String getDeptCode()
    {
        return getTokenUser().getDeptCode();
    }

    public static TokenUser getTokenUser() {
        try {
            TokenUser tokenUser = (TokenUser) ServletUtils.getHttpServletRequest().getAttribute("tokenUser");
            return tokenUser;
        } catch (Exception e) {
            throw new LoginException(ResponseEnum.LOGIN_ERROR);
        }

    }
    public static String getToken() {
        try {
            return    ServletUtils.getHttpServletRequest().getHeader("Authorization");
        } catch (Exception e) {
            throw new LoginException(ResponseEnum.LOGIN_ERROR);
        }

    }

    /**
     * 获取token中的用户信息
     * @param token
     * @return
     */
    public static TokenUser getTokenToUser(String token){
        try {
            if(StringUtil.isEmpty(token)){
               return null;
            }
            token = Base64.decode(token);
            DESCrypt crypt = new DESCrypt();
            String tokenJson = new String (crypt.decrypt(token),"UTF-8");

            if(tokenJson !=null && tokenJson.contains("[")){
                return  JSONArray.parseArray(tokenJson,TokenUser.class).get(0);
            }else{
                return JSONArray.parseObject(tokenJson,TokenUser.class);
            }
        } catch (Exception e) {
            throw new LoginException(ResponseEnum.LOGIN_ERROR);
        }
    }

    /**
     * 根据用户信息生成token
     * @param user
     * @return
     */
    public static String getTokenUserToToken(TokenUser user){
        try {
            if(user == null){
                return null;
            }
            String json= JSONArray.toJSONString(user);
            DESCrypt crypt = new DESCrypt();
            String ntoken=crypt.encrypt(json.getBytes("UTF-8"));
            return Base64.encode(ntoken);
        } catch (Exception e) {
            throw new LoginException(ResponseEnum.LOGIN_ERROR);
        }
    }

}
